import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { Cat } from './interface/cat.interface';
import { InjectRepository } from '@nestjs/typeorm';
import { Cats } from './cats.entity';
import {
  CurrentUser,
  ApiResult,
  ErrorCode,
  BusinessException,
} from '../config/index';
import { Repository } from 'typeorm';
import { CreateCats } from './dto/createCats.dto';
import { UpdateCats } from './dto/updateCats.dto';
import { DeleteById } from './dto/deleteById.dto';

@Injectable()
export class CatsService {
  constructor(
    @InjectRepository(Cats)
    private readonly catsRepository: Repository<Cats>,
  ) {}

  async findAll(): Promise<any> {
    const cats: Cat[] = await this.catsRepository.find();

    return { cats };
  }

  async findById(id: string): Promise<Cat[]> {
    return await this.catsRepository.find({ where: { id } });
  }
  /**
   *
   * @param payload 添加一个Cats
   */
  async add(payload: CreateCats): Promise<Cats> {
    return await this.catsRepository.save(this.catsRepository.create(payload));
  }
  /**
   *
   * @param payload 更新Cats 新增加业务异常处理类型
   */
  async update(payload: UpdateCats): Promise<Cats | any> {
    const cats: Cats = await this.catsRepository.findOne(payload.id);
    if (!cats) {
      BusinessException.throwBusinessException(ErrorCode.ERR_10005());
    }
    return await this.catsRepository.save(payload);
  }

  async delete(payload: DeleteById): Promise<void> {
    await this.catsRepository.delete(payload);
  }
  /**
   *
   * @param payload 根据age、name查询Cats
   */
  async selectCats(payload: CreateCats): Promise<Cats> {
    return await this.catsRepository
      .createQueryBuilder('cats')
      .where('age=:age and name=:name', {
        age: payload.age,
        name: payload.name,
      })
      .getOne();
  }
}
